﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Transactions;

namespace _17_ActionFilter.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class Demo1Controller : ControllerBase
    {
        private readonly MyDbContext db;
        public Demo1Controller(MyDbContext db)
        {
            this.db = db;
        }
        [NotTransation] //不启动filter事务
        // 同步事务
        [HttpGet]
        public string Add()
        {
            using (TransactionScope tx = new TransactionScope())
            {

                db.Books17.Add(new Book
                {
                    Name = "A1111",
                    Price = 1,
                });
                db.SaveChanges();
                db.Persons17.Add(new Person
                {
                    Name = "Bdsfsdafdsfsdafdsfsdfdsf",
                    Age = 18
                });
                db.SaveChanges();
                tx.Complete();
                return "ok";

            }

        }
        [NotTransation] //不启动filter事务
        // 异步事务
        [HttpGet]
        public async Task<string> Add1()
        {
            using (TransactionScope tx = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {

                db.Books17.Add(new Book
                {
                    Name = "A1111",
                    Price = 1,
                });
                await db.SaveChangesAsync();
                db.Persons17.Add(new Person
                {
                    Name = "Bdsfsdafdsfsdafdsfsdfdsf",
                    Age = 18
                });
                await db.SaveChangesAsync();
                tx.Complete();
                return "ok";

            }

        }
        [HttpGet]
        public async Task<string> Add2()
        {
            db.Books17.Add(new Book
            {
                Name = "A222",
                Price = 1,
            });
            await db.SaveChangesAsync();
            db.Persons17.Add(new Person
            {
                Name = "Bdsfsdafdsfsdafdsfsdfdsf",
                Age = 18
            });
            await db.SaveChangesAsync();
                
            return "ok";

            

        }





    }
}
